package com.alibaba.japan.club.runtime.springmvc.module;

import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 该类是此框架的核心类<br>
 * 主要的功能是提供的一些方法可以实现对request、screen和controller等相关的操作
 * 
 * @author:shaochuan.wangsc
 * @date:2009-3-24
 * 
 */
public class ModuleHelper {

	public static final String SPLIT_CHARACTER = "/";

	public static final String PACKAGE_CHARACTER = ".";

	public static final Pattern URL_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");

	public static final Pattern SPLIT_PATTERN = Pattern.compile("[/]+");

	public static final Pattern PACKAGE_PATTERN = Pattern.compile("[.]");

	public static final String SCREEN_PACKAGE = "screen";

	public static final Pattern SCREEN_PATTERN = Pattern.compile("Screen$");

	public static final String CONTROL_PACKAGE = "control";

	public static final Pattern CONTROLLER_PATTERN = Pattern.compile("Controller$");

	public static final Pattern CONTROL_PACKAGE_PATTERN = Pattern.compile(SPLIT_CHARACTER + CONTROL_PACKAGE + SPLIT_CHARACTER);

	/**
	 * 通过类名来判断当前类是否是ScreenBean
	 * 
	 * @param className
	 * @return
	 */
	public static boolean isScreenBean(String className) {
		if (className == null || "".equals(className)) {
			return false;
		}
		if (SCREEN_PATTERN.matcher(className).find()) {
			return true;
		}
		return false;
	}

	/**
	 * 通过类名来判断当前类是否是ControllerBean
	 * 
	 * @param className
	 * @return
	 */
	public static boolean isControllerBean(String className) {
		if (className == null || "".equals(className)) {
			return false;
		}
		if (CONTROLLER_PATTERN.matcher(className).find()) {
			return true;
		}
		return false;
	}

	/**
	 * 通过请求的path来定位要访问的freemarker页面
	 * 
	 * @param modulePattern
	 * @param path
	 * @return
	 */
	public static String getFreemarkerPath(ModulePattern modulePattern, String path) {
		String freemarkerPath = null;
		Map<String, String> moduleMapping = modulePattern.getModuleMapping();
		String bestPathMatch = null;
		for (Entry<String, String> element : moduleMapping.entrySet()) {
			String registeredModule = element.getKey();
			if (path != null && path.startsWith(registeredModule) && (bestPathMatch == null || bestPathMatch.length() < registeredModule.length())) {
				bestPathMatch = registeredModule;
			}
		}
		if (bestPathMatch != null) {
			freemarkerPath = path.replaceFirst(bestPathMatch, moduleMapping.get(bestPathMatch));
			freemarkerPath = URL_EXTENSION_PATTERN.matcher(freemarkerPath).replaceAll("");
		}
		return freemarkerPath;
	}

	/**
	 * 通过.ftl的文件路径来获得系统中所注册的screen类名
	 * 
	 * @param file
	 * @return
	 */
	public static String getScreenBeanName(String file) {
		if (file == null || "".equals(file)) {
			return "";
		}

		StringBuilder screenClassName = new StringBuilder();
		String fileName = dropUriExtension(file);
		fileName = SPLIT_CHARACTER + fileName + SPLIT_CHARACTER;
		fileName = SPLIT_PATTERN.matcher(fileName).replaceAll(SPLIT_CHARACTER);
		fileName = fileName.substring(1, fileName.length() - 1);

		String[] temp = fileName.split(SPLIT_CHARACTER);
		for (int i = 0; i < temp.length; i++) {
			if (i == 0) {
				screenClassName.append(SPLIT_CHARACTER + temp[i] + SPLIT_CHARACTER + SCREEN_PACKAGE);
			} else {
				screenClassName.append(SPLIT_CHARACTER + temp[i]);
			}
		}
		return screenClassName.toString();
	}

	/**
	 * 去掉uri的后缀扩展名
	 * 
	 * @param uri
	 * @return
	 */
	public static String dropUriExtension(String uri) {
		return URL_EXTENSION_PATTERN.matcher(uri).replaceAll("");
	}

	/**
	 * 获得uri的后缀扩展名
	 * 
	 * @param uri
	 * @return
	 */
	public static String getUriExtension(String uri) {
		Matcher matcher = URL_EXTENSION_PATTERN.matcher(uri);
		if (matcher.find()) {
			return matcher.group();
		}
		return "";
	}

	/**
	 * 通过className生成spring注册文件中的screenBeanName
	 * 
	 * @param className
	 * 
	 * @return
	 */
	public static String makeScreenBeanName(ModulePattern modulePattern, String className) {
		if (!SCREEN_PATTERN.matcher(className).find()) {
			return "";
		}
		return makeBeanName(modulePattern, className, 1);
	}

	/**
	 * 通过className生成spring注册文件中的controlBeanName
	 * 
	 * @param className
	 * @param type 1.screen 2.control
	 * @return
	 */
	public static String makeControlBeanName(ModulePattern modulePattern, String className) {
		if (!CONTROLLER_PATTERN.matcher(className).find()) {
			return "";
		}
		return makeBeanName(modulePattern, className, 2);
	}

	/**
	 * 生成spring注册文件中的beanName,并去掉相关文件名,如: <br>
	 * <code>
	 * 		/home/screen/IndexScreen -> /home/screen/index<br>
	 * 		/home/control/IndexController -> /home/control/index
	 * </code>
	 * 
	 * @param className
	 * @param type 1.screen 2.control
	 * @return
	 */
	private static String makeBeanName(ModulePattern modulePattern, String className, int type) {
		String beanName = "";
		beanName = className.replace(modulePattern.getPackagePath(), "");
		beanName = PACKAGE_PATTERN.matcher(beanName).replaceAll(SPLIT_CHARACTER);

		StringBuilder sb = new StringBuilder();
		if (type == 1) {
			String[] temp = beanName.split(SPLIT_CHARACTER);
			for (int i = 0; i < temp.length; i++) {
				if (i == temp.length - 1) {
					String name = SCREEN_PATTERN.matcher(temp[i]).replaceAll("");
					sb.append(SPLIT_CHARACTER + name.substring(0, 1).toLowerCase() + name.substring(1));
				} else {
					sb.append(SPLIT_CHARACTER + temp[i]);
				}
			}
		}
		if (type == 2) {
			String[] temp = beanName.split(SPLIT_CHARACTER);
			for (int i = 0; i < temp.length; i++) {
				if (i == temp.length - 1) {
					String name = CONTROLLER_PATTERN.matcher(temp[i]).replaceAll("");
					sb.append(SPLIT_CHARACTER + name.substring(0, 1).toLowerCase() + name.substring(1));
				} else {
					sb.append(SPLIT_CHARACTER + temp[i]);
				}
			}
		}
		return SPLIT_PATTERN.matcher(sb.toString()).replaceAll(SPLIT_CHARACTER);
	}

	/**
	 * 通过controlBeanName来生成urlMap中的key值
	 * 
	 * @param controlBeanName
	 * @return
	 */
	public static String makeUrlMappingKey(ModulePattern modulePattern, String controlBeanName) {
		Map<String, String> moduleMapping = modulePattern.getModuleMapping();

		String urlKey = null;
		String bestModuleMatch = null;
		for (Entry<String, String> element : moduleMapping.entrySet()) {
			String registeredModule = element.getKey();
			String registeredModuleValue = element.getValue();

			Pattern firstPattern = Pattern.compile("^" + registeredModuleValue);
			Matcher firstMatcher = firstPattern.matcher(controlBeanName);
			if (firstMatcher.find() && (bestModuleMatch == null || bestModuleMatch.length() < registeredModule.length())) {
				bestModuleMatch = registeredModule;
				urlKey = firstMatcher.replaceAll(registeredModule);
			}
		}
		return (bestModuleMatch == null) ? "" : CONTROL_PACKAGE_PATTERN.matcher(urlKey).replaceAll(SPLIT_CHARACTER) + modulePattern.getUrlPattern();
	}
}
